package com.cory.admin.sys.core.privilege.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.cory.admin.sys.config.AdminConstants;
import com.cory.admin.sys.domain.AdminPrincipal;
import com.cory.boot.config.FreemarkerConfig.FreemarketTag;
import com.cory.boot.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author xiongcong
 * @date 2022-05-02
 */
@Component
@FreemarketTag(name = "areAnyUserType", prefix="privilege")
public class AreAnyUserTypeTag implements TemplateDirectiveModel {
    private static final String PARAM_NAME = "userTypes";

    @Autowired
    private HttpServletRequest request;

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        List<Integer> userTypes = FreeMarkerUtils.getParameter(PARAM_NAME, List.class, params);
        
        boolean areUserType;
        AdminPrincipal principal = (AdminPrincipal)request.getSession().getAttribute(AdminConstants.SESSION_USER_INFO);
        if (CollectionUtils.isEmpty(userTypes) || principal == null || principal.getUserType() == null) {
            areUserType = false;
        } else {
            areUserType = userTypes.stream().anyMatch(principal.getUserType()::equals);
        }
        
        if (areUserType && body != null)
            body.render(env.getOut());
    }
}
